package com.smartcommunity.base.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * @ClassName FeignClientsConfigurationCustom
 * @Author lilun
 * @Description feign调用时保证session不丢失
 * @Date 2020/1/20 17:40
 * @Version 1.0
 */

@Configuration
@EnableFeignClients(basePackages = "com.smartcommunity.api")
public class FeignClientsConfigurationCustom implements RequestInterceptor {


    // * 使用此方法要注意，所有的请求头部全部放进去，可能会报下面错误
    //     * Incomplete output stream executing POST
    @Override
    public void apply(RequestTemplate template) {

        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null) {
            return;
        }

        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        Enumeration<String> headerNames = request.getHeaderNames();
        if (headerNames != null) {
            while (headerNames.hasMoreElements()) {
                String name = headerNames.nextElement();
                // post请求获取的是前端请求内容的长度，调用feign接口请求的长度和此长度不一样，
                // 会有【Incomplete output stream executing POST】异常。
                // 过滤掉content-length，测试正常
                if(name.equals("content-length")){
                    continue;
                }
                Enumeration<String> values = request.getHeaders(name);
                while (values.hasMoreElements()) {
                    String value = values.nextElement();
                    template.header(name, value);
                }
            }
        }
    }


    }
